﻿Imports System.Data.SqlClient
Imports System.IO
Imports System.IO.Compression

Partial Class str_itasset
    Inherits System.Web.UI.Page
    Sub ResetText()
        txtassignedTo.Text = ""
        txtCurrentAssignee.Text = ""
        txtYearAcquired.Text = ""
        txtDatePurchased.Text = ""
        txtSupplier.Text = ""
        txtDateDelivered.Text = ""
        txtdevicetype.Text = ""
        txtserial.Text = ""
        txtbrand.Text = ""
        txtmodel.Text = ""
        txtspecss.Text = ""
        txtpo.Text = ""
        txtwarranty.Text = ""
        txtcost.Text = ""
        txtinvoice.Text = ""
        txtrecieved.Text = ""
        txtdaterecieved.Text = ""
        txtdeployedby.Text = ""
        txtdatedeployement.Text = ""
        txtstatus.Text = ""
        txtlanip.Text = ""
        txtgatewayip.Text = ""
        txtos.Text = ""
        txtother1.Text = ""
        txtother2.Text = ""
        Try
            txtAssetEndingID.DataBind()
        Catch ex As Exception

        End Try
    End Sub
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Session("DateNow") = Now.ToString
        If txtassignedTo.Text = "" Then
            Return
        End If
        'If txtCurrentAssignee.Text = "" Then
        'Return
        'End If
        If DropDownList1.SelectedValue = "Select Company" Then
            Dim err As New CustomValidator
            err.IsValid = False
            err.ErrorMessage = "* Invalid Company"
            Page.Validators.Add(err)
            Return
        End If
        If DropDownList2.SelectedValue = "Select Store" Then
            Dim err As New CustomValidator
            err.IsValid = False
            err.ErrorMessage = "* Invalid Store"
            Page.Validators.Add(err)
            Return
        End If
        If lstAssetClass.SelectedValue = "Select Asset Class" Then
            Dim err As New CustomValidator
            err.IsValid = False
            err.ErrorMessage = "* Invalid Asset Class"
            Page.Validators.Add(err)
            Return
        End If
        If txtDatePurchased.Text = "" Then
            Return
        End If
        If txtSupplier.Text = "" Then
            Return
        End If
        If txtDateDelivered.Text = "" Then
            Return
        End If
        'If txtAssetno.Text = "" Then
        '    Return
        'End If
        If txtdevicetype.Text = "" Then
            Return
        End If
        If txtserial.Text = "" Then
            Return
        End If
        If txtbrand.Text = "" Then
            Return
        End If
        If txtpo.Text = "" Then
            Return
        End If
        If txtwarranty.Text = "" Then
            Return
        End If
        If txtcost.Text = "" Then
            Return
        End If
        If txtrecieved.Text = "" Then
            Return
        End If
        If txtstatus.Text = "" Then
            Return
        End If
        Try
            'check if duplicate
            Dim EndingID As Integer = Integer.Parse(txtAssetEndingID.SelectedValue)
CheckDuplicate:
            Session("AssetID") = DropDownList1.SelectedValue & "-" & lstAssetClass.SelectedValue & "-" & EndingID
            Dim dupcon = New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
            Dim dup = New SqlCommand()
            dup.CommandText = "Select [assetno] from [Management_Info_Sys].[dbo].[ita_items] where [assetno] = '" & Session("AssetID") & "'"
            dup.Connection = dupcon
            dupcon.Open()
            Dim record As Integer = 0
            record = dup.ExecuteScalar()
            dupcon.Close()
            If record > 0 Then
                EndingID += 1
                GoTo CheckDuplicate
            Else
                Session("AssetID") = DropDownList1.SelectedValue & "-" & lstAssetClass.SelectedValue & "-" & EndingID
                'Update Counter
                Dim upcon = New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
                Dim up = New SqlCommand()
                up.CommandText = "Update [Management_Info_Sys].[dbo].[numbercounter] set [ita_assetnumber]=" & EndingID + 1
                up.Connection = upcon
                upcon.Open()
                up.ExecuteNonQuery()
                upcon.Close()
            End If


            SqlDataSource2.Insert()

            'Upload Image
            If FileUpload1.HasFile = True Then
                Dim MIMEType As String = Nothing
                Dim extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower()

                Select Case extension
                    Case ".gif"
                        MIMEType = "image/gif"
                    Case ".jpg", ".jpeg", ".jpe"
                        MIMEType = "image/jpeg"
                    Case ".png"
                        MIMEType = "image/png"

                    Case Else
                        'Invalid file type uploaded
                        MIMEType = "Invalid Image"
                        Dim err As New CustomValidator
                        err.IsValid = False
                        err.ErrorMessage = "Invalid Image"
                        Page.Validators.Add(err)
                        Exit Sub
                End Select

                If MIMEType <> "Invalid Image" Then
                    'Clear Image
                    Dim delcon = New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
                    Dim del = New SqlCommand()
                    del.CommandText = "Delete [Management_Info_Sys].[dbo].[img_items] where [img_table] = 'ita_items" & Session("AssetID") & "'"
                    del.Connection = delcon
                    delcon.Open()
                    del.ExecuteNonQuery()
                    delcon.Close()
                    'Add
                    Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
                        Const SQL As String = "INSERT INTO [img_items] ([img_table], [img_desc], [img]) VALUES (@img_table, @img_desc, @img)"
                        Dim myCommand As New SqlCommand(SQL, myConnection)
                        'myCommand.Parameters.AddWithValue("@img_desc", FileUpload1.FileName.Trim)
                        myCommand.Parameters.AddWithValue("@img_table", "ita_items" & Session("AssetID"))
                        myCommand.Parameters.AddWithValue("@img_desc", MIMEType)

                        'Load FileUpload's InputStream into Byte array
                        Dim imageBytes(FileUpload1.PostedFile.InputStream.Length) As Byte
                        FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
                        myCommand.Parameters.AddWithValue("@img", Compress(imageBytes))

                        myConnection.Open()
                        myCommand.ExecuteNonQuery()
                        myConnection.Close()
                    End Using
                End If
            End If
            'EndingID
            txtAssetEndingID.Items.Add(EndingID + 1)
            txtAssetEndingID.SelectedValue = EndingID + 1

            lblLogs.CssClass = "SuccessLogs"
            lblLogs.Text = "Success"
            lblLogs.Visible = True

            'Dim err As New CustomValidator
            'err.CssClass = "SuccessLogs"
            'err.IsValid = True
            'err.ErrorMessage = "Success"
            'Page.Validators.Add(err)

            ResetText()
        Catch ex As Exception
            'lblLogs.CssClass = "ErrorLogs"
            'lblLogs.Text = "Failed Because : " & ex.Message
            'lblLogs.Visible = True

            Dim err As New CustomValidator
            err.CssClass = "ErrorLogs"
            err.IsValid = False
            err.ErrorMessage = ex.Message
            Page.Validators.Add(err)
        End Try
    End Sub

    Protected Sub Page_DataBinding(sender As Object, e As EventArgs) Handles Me.DataBinding
        ''storename
        'DropDownList2.DataSource = SqlDataSource1
        'DropDownList2.DataTextField = "storename"
        'DropDownList2.DataValueField = "storename"
        'DropDownList2.DataBind()
        'DropDownList2.Items.Add("Select a Store")
        'DropDownList2.SelectedValue = "Select a Store"
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Session("IdentityName") = Context.User.Identity.Name.ToString()
        
    End Sub
    Public Shared Function Compress(bytes As Byte()) As Byte()
        Dim stream = New MemoryStream()
        Dim zipStream = New DeflateStream(stream, CompressionMode.Compress, True)
        zipStream.Write(bytes, 0, bytes.Length)
        zipStream.Close()
        Return stream.ToArray()
    End Function

   
    Protected Sub Page_LoadComplete(sender As Object, e As EventArgs) Handles Me.LoadComplete
        'lstAssetClass.DataSource = assetSource
        'lstAssetClass.DataTextField = "assetclass"
        'lstAssetClass.DataValueField = "assetclass"
        'lstAssetClass.DataBind()
        'lstAssetClass.Items.Add("Select Asset Class")
        'lstAssetClass.SelectedValue = "Select Asset Class"
    End Sub

    Protected Sub SqlDataSource2_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource2.Selecting

    End Sub
End Class
